<?php
declare (strict_types=1);

namespace app\api\controller;

use addons\OssBackup\facade\OssBackup;
use app\common\model\Logs;
use app\common\model\Statistics;
use app\common\model\Order;
use app\common\model\User;
use app\common\model\OrderTemporary;
use app\common\model\PreceptOrder;

class Callback
{

    /**
     * @return void
     * 自动备份
     */
    public function autoOssBackup()
    {
        try {
            $route = 'callback/autoOssBackup.log';
            $result = OssBackup::auto();
            Logs::write($route, json_encode($result));
        } catch (\Exception $e) {
            Logs::write($route, $e->getMessage());
        }
    }

    /**
     * @return void
     * 更新统计
     */
    public function statistics()
    {
        Statistics::_timing();
    }


    public function alipayCallback()
    {
        try {
            $route = 'callback/alipayCallback.log';
            $pay = \AliPay\App::instance(config('pay')['alipay']);
            $data = $pay->notify();
            if (in_array($data['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED'])) {
                // @todo 更新订单状态，支付完成

                Logs::write($route, '订单支付成功');
                return 'SUCCESS';
            } else {
                // @todo 回调验证失败处理
                Logs::write($route, '回调验证失败:' .json_encode($data));

            }
        } catch (\Exception $e) {
            // @todo 异常处理
            Logs::write($route, $e->getMessage());
        }
    }
    /**
     * 微信支付回调
     */
    public function wechatCallback()
    {
        try {
            $route = 'callback/wechatCallback.log';
            $wechat = \WeChat\Pay::instance(config('pay')['wechat']);
            $data = $wechat->getNotify();
            if ($data['return_code'] === 'SUCCESS' && $data['result_code'] === 'SUCCESS') {
                // @todo 更新订单状态，支付完成
                $info = Order::where(['sn' => $data['out_trade_no']])->find();
                if ($info && $info->pay_state == 0) {
                    $result = OrderTemporary::operations($info, User::where(['id' => $info['uid']])->find(), 'wechat');
                    if ($result['code'] == 1) {
                        Logs::writeLog($route, '成功，订单号:' . $info->sn);
                        return $wechat->getNotifySuccessReply();
                    } else {
                        Logs::writeLog($route, '失败，订单号:' . $info->sn . '->' . $result['msg']);
                    }
                } else {
                    Logs::writeLog($route, '未查询到订单');
                }
            } else {
                // @todo 回调验证失败处理
                Logs::writeLog($route, '回调验证失败：' . json_encode($data));
            }
        } catch (\Exception $e) {
            // @todo 异常处理
            Logs::writeLog($route, $e->getMessage());

        }
    }
    /**
     * 方案支付回调
     */
    public function wechatPreceptOrder()
    {
        try {
            $route = 'callback/wechatPreceptOrder.log';
            $wechat = \WeChat\Pay::instance(config('pay')['wechat']);
            $data = $wechat->getNotify();
            if ($data['return_code'] === 'SUCCESS' && $data['result_code'] === 'SUCCESS') {
                // @todo 更新订单状态，支付完成
                $info = PreceptOrder::where(['sn' => $data['out_trade_no']])->find();
                if ($info && $info->pay_state == 0) {
                    $result = PreceptOrder::operations($info, User::where(['id' => $info['uid']])->find(), 'wechat');
                    if ($result['code'] == 1) {
                        Logs::writeLog($route, '成功，订单号:' . $info->sn);
                        return $wechat->getNotifySuccessReply();
                    } else {
                        Logs::writeLog($route, '失败，订单号:' . $info->sn . '->' . $result['msg']);
                    }
                } else {
                    Logs::writeLog($route, '未查询到订单');
                }
            } else {
                // @todo 回调验证失败处理
                Logs::writeLog($route, '回调验证失败：' . json_encode($data));
            }
        } catch (\Exception $e) {
            // @todo 异常处理
            Logs::writeLog($route, $e->getMessage());

        }
    }
       /**
     * 消息推送
     */
    public function checkSignature() {
        $route = 'callback/confirm_receive.log';
        if(request()->isPost()){
            try {
                $postStr = file_get_contents('php://input');
                if($postStr){
                    $postdata = json_decode($postStr,true);
                    /**
                     * 消息推送确认收货
                     */
                    if($postdata['MsgType']  == 'event' && $postdata['Event'] == 'trade_manage_order_settlement'){
                        if(!empty($postdata['confirm_receive_method'])){
                            $data['status'] = 3;
                            $data['receipt_time'] = $postdata['confirm_receive_time'];
                            OrderTemporary::where('sn',$postdata['merchant_trade_no'])->update($data);
                            Logs::writeLog($route, '确认收货时间：'.date('Y-m-d H:i:s',$postdata['confirm_receive_time']) .'订单号：'.$postdata['merchant_trade_no']);
                            exit('success');
                        }
                    }
                }
            } catch (\Exception $e) {
                Logs::writeLog($route, $e->getMessage());
            }
        }else{
            $signature = $_GET["signature"];
            $timestamp = $_GET["timestamp"];
            $nonce = $_GET["nonce"];
            $token = config('pay.wechat.token');
            $tmpArr = array($token, $timestamp, $nonce);
            sort($tmpArr, SORT_STRING);
            $tmp = sha1(implode($tmpArr));
            if($tmp == $signature){
                ob_clean();
                exit(htmlspecialchars($_GET['echostr']));
            }else{
                return false;
            }
        }
     }


}